package com.shiwaixiangcun.customer.module.intelligent

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CameraDetail
import com.shiwaixiangcun.customer.entity.DeviceBaseEntity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.ResponseConfig.SUCCESS
import com.shiwaixiangcun.customer.network.StringDialogCallBack
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import kotlinx.android.synthetic.main.activity_smart_camera.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 智能摄像头设备信息
 */
class SmartCameraInfoActivity : BaseActivity(), View.OnClickListener {
    val MODIFY_CAMERA_NAME = 0x0002
    private var isOnline = false
    private var REQUEST_DATA = 2

    private var deviceId: String? = null
    private var strToken: String? = null
    private var cameraId: Long = 0
    private var channelId: Int = 0
    val UNBIND = 2
    override fun onClick(view: View?) {
        val bundle = Bundle()

        when (view?.id) {
            R.id.back_left -> finish()
            R.id.llayout_camera_name -> {
                bundle.putLong("camera_id", cameraId)
                readyGoForResult(SmartCameraNameActivity::class.java, MODIFY_CAMERA_NAME, bundle)
            }
            R.id.btn_unbind -> showDialog("您确定要解绑智能摄像机吗？\n这将会重置智能摄像机为初始状态，\n摄像机分享也将会被清除", "解除绑定")
            R.id.rlayout_share_camera -> {
                bundle.putInt("channelId", channelId)
                bundle.putString("deviceId", deviceId)
                readyGo(ShareCameraActivity::class.java, bundle)

            }
            R.id.layout_camera_off -> {
                bundle.putString("device_type", "camera")
                readyGo(SmartCameraOffReasonActivity::class.java, bundle)
            }

        }
    }

    override fun onRestart() {
        super.onRestart()
        initData()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_smart_camera)

        EventUtil.getInstance().register(this)


        initBundleData()
        initData()
        initViewAndEvent()
    }

    override fun onPause() {
        super.onPause()
        EventUtil.getInstance().unregister(this)
    }


    /**
     * 更新界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.CAMERA_DETAIL) {
            return
        }
        when (simpleEvent.mEventValue) {
            REQUEST_DATA -> {

                var cameraDetail = simpleEvent.data as CameraDetail
                tv_number_info.text = "摄像机已经分享给${cameraDetail.shareCameraNumber}个用户"
                tv_camera_name.text = cameraDetail.name
                cameraId = cameraDetail.cameraId
                channelId = cameraDetail.data.channels[0].channelId
            }
            UNBIND -> {
            }
        }

    }

    private fun initBundleData() {
        deviceId = intent.extras.getString("deviceId")
        isOnline = intent.extras.getBoolean("deviceIsOnline")

    }

    private fun initData() {

        strToken = AppSharePreferenceMgr.get(this, ConfigSps.CURRENT_TOKEN, "") as String
        OkGo.get<String>(GlobalApi.getCameraDetail)
                .params("access_token", strToken)
                .params("deviceId", deviceId)
                .execute(object : StringDialogCallBack(this) {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseEntity<CameraDetail>>() {}.type
                        val fromJson = Gson().fromJson<DeviceBaseEntity<CameraDetail>>(response?.body(), type)

                        when (fromJson.responseCode) {
                            SUCCESS -> {
                                Log.e(BUG_TAG, "请求成功")
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.CAMERA_DETAIL, REQUEST_DATA, fromJson.data))

                            }
                        }

                    }
                })
    }

    private fun initViewAndEvent() {
        tv_page_name.text = "智能摄像头"
        tv_page_name.setTextColor(resources.getColor(R.color.ui_white))
        if (isOnline) {
            tv_camera_on.visibility = View.VISIBLE
            layout_camera_off.visibility = View.GONE
            iv_bg.setImageResource(R.drawable.camera_on)
        } else {
            tv_camera_on.visibility = View.GONE
            layout_camera_off.visibility = View.VISIBLE
            iv_bg.setImageResource(R.drawable.camera_off)
        }
        layout_camera_off.setOnClickListener(this)
        back_left.setOnClickListener(this)
        llayout_camera_name.setOnClickListener(this)
        btn_unbind.setOnClickListener(this)
        rlayout_share_camera.setOnClickListener(this)
        rlayout_share_camera.setOnClickListener(this)

    }


    private fun showDialog(title: String, content: String) {
        val dialog = DialogLoginOut(mContext, R.layout.item_dialog_loginout)
        dialog.setTitle(title)
        dialog.setNoOnclickListener("返回", {
            dialog.dismiss()
        })
        dialog.setYesOnclickListener(content, {
            unBindCamera()
            dialog.dismiss()
        })
        dialog.show()
    }

    /**
     * 摄像头解除绑定
     *
     */
    private fun unBindCamera() {
        OkGo.delete<String>(GlobalApi.unbindCamera)
                .params("access_token", strToken)
                .params("deviceId", deviceId)
                .isSpliceUrl(true)
                .execute(object : StringDialogCallBack(this) {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<DeviceBaseEntity<Any>>() {}.type
                        val fromJson = JsonUtil.fromJson<DeviceBaseEntity<Any>>(response?.body(), type)
                        when (fromJson.responseCode) {
                            SUCCESS -> {
                                showToastShort("解除绑定成功")
                                finish()
                            }

                        }
                    }

                })


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == 2) {
            if (requestCode == MODIFY_CAMERA_NAME) {
                val cameraName = data.getStringExtra("camera_name")
                //设置结果显示框的显示数值
                tv_camera_name.text = (cameraName.toString())
            }
        }
    }
}
